<?php
namespace phpsms;

class Dahantc {
    private $url = "http://wt.3tong.net/json/sms";
    private $account = "dh49295";
    private $password = "513ktGCA";

    public function sendSms($phones, $template, $variables, $msgid, $sendtime)
    {
        $data = [
            'account' => $this->account,
            'password' => md5($this->password),
            'template' => [
                'id' => $template,
                'variables' => $variables
            ],
            'msgid' => $msgid,
            'phones' => $phones,
            'sendtime' => $sendtime
        ];

        $result = $this->http_post_json($this->url . '/Submit', json_encode($data));
        if (is_string($result)) {
            $result = json_decode($result, true);
        }
        if (is_array($result)) {
            $result = ['Message' => $result['result'] == '0' ? "OK" : $result['desc']];
        } else {
            $result = ['Message' => '发生错误'];
        }

        return $result;
    }

    private function http_post_json($url, $data)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen($data)]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $ret = curl_exec($ch);
        curl_close($ch);
        return $ret;
    }
}
